package com.wstuo.common.security.service;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.exception.ApplicationException;
import com.wstuo.common.file.csv.CSVReader;
import com.wstuo.common.file.csv.CSVWriter;
import com.wstuo.common.security.dao.ICompanyDAO;
import com.wstuo.common.security.dao.ICustomerDAO;
import com.wstuo.common.security.dao.IOrganizationDAO;
import com.wstuo.common.security.dto.CustomerDTO;
import com.wstuo.common.security.dto.CustomerQueryDTO;
import com.wstuo.common.security.dto.OrganizationDTO;
import com.wstuo.common.security.entity.Company;
import com.wstuo.common.security.entity.Customer;
import com.wstuo.common.security.entity.Organization;
import com.wstuo.common.security.utils.FileEncodeUtils;
import com.wstuo.common.security.utils.LanguageContent;
import com.wstuo.common.util.StringUtils;

/**
 * 客户业务类
 */
public class CustomerService implements ICustomerService {
	private static final Logger LOGGER = Logger.getLogger(CustomerService.class);
	@Autowired
	private ICustomerDAO customerDAO;
	@Autowired
	private ICompanyDAO companyDAO;
	@Autowired
	private IOrganizationDAO organizationDAO;

	/**
	 * 分页查询数据.
	 * 
	 * @param customerQueryDTO
	 *            分页查询DTO：CustomerQueryDTO
	 * @param sidx
	 * @param sord
	 * @return 分页数据：PageDTO
	 */
	@SuppressWarnings("unchecked")
	public PageDTO findPagerCustomer(CustomerQueryDTO customerQueryDTO, String sidx, String sord) {
		PageDTO p = customerDAO.findPager(customerQueryDTO, sidx, sord);
		List<Customer> entities = (List<Customer>) p.getData();

		List<CustomerDTO> dtos = new ArrayList<CustomerDTO>();

		for (Customer cus : entities) {
			CustomerDTO dto = new CustomerDTO();
			CustomerDTO.entity2dto(cus, dto);
			if (cus.getParentOrg() != null) {
				dto.setCompanyNo(cus.getParentOrg().getOrgNo());
			}

			if (cus.getCompanyNo() != null && cus.getCompanyNo() != 0) {

				dto.setCompanyName(companyDAO.findById(cus.getCompanyNo()).getOrgName());
			}
			// 查找类型
			dtos.add(dto);
		}

		p.setData(dtos);

		return p;
	}

	/**
	 * 新增客户.
	 * 
	 * @param dto
	 *            机构DTO：OrganizationDTO
	 */
	@Transactional()
	public void saveCustomer(OrganizationDTO dto) {
		Customer customer = new Customer();
		dto2entity(dto, customer);
		customer.setCompanyNo(dto.getCompanyNo());
		if (dto.getParentOrgNo() != -1) {
			Company company = companyDAO.findById(dto.getParentOrgNo());
			customer.setParentOrg(company);
		}
		customerDAO.save(customer);
		dto.setOrgNo(customer.getOrgNo());
	}

	/**
	 * 新增客户.
	 * 
	 * @param dto
	 *            客户DTO：CustomerDTO
	 */
	@Transactional()
	public void saveCustomer(CustomerDTO dto) {
		Customer customer = new Customer();
		dto2entity(dto, customer);
		customer.setCompanyNo(dto.getCompanyNo());
		customerDAO.save(customer);
		dto.setOrgNo(customer.getOrgNo());
	}

	/**
	 * dto to entity
	 */
	private void dto2entity(OrganizationDTO dto,Customer customer){
		customer.setOrgName(dto.getOrgName());
		customer.setOfficeFax(dto.getOfficeFax());
		customer.setOfficePhone(dto.getOfficePhone());
		customer.setEmail(dto.getEmail());
		customer.setAddress(dto.getAddress());
	}
	
	/**
	 * dto to entity
	 */
	private void dto2entity(CustomerDTO dto,Customer customer){
		customer.setOrgName(dto.getOrgName());
		customer.setOfficeFax(dto.getOfficeFax());
		customer.setOfficePhone(dto.getOfficePhone());
		customer.setEmail(dto.getEmail());
		customer.setAddress(dto.getAddress());
		if (dto.getCompanyNo() != null) {
			customer.setParentOrg(companyDAO.findById(dto.getCompanyNo()));
		}
	}
	/**
	 * 修改客户信息.
	 * 
	 * @param dto
	 *            客户DTO：CustomerDTO
	 */
	@Transactional()
	public void mergeCustomer(CustomerDTO dto) {
		Customer customer = customerDAO.findById(dto.getOrgNo());
		dto2entity(dto, customer);
		customerDAO.merge(customer);
	}

	/**
	 * 修改客户信息.
	 * 
	 * @param dto
	 *            机构DTO：OrganizationDTO
	 */
	@Transactional()
	public void mergeCustomer(OrganizationDTO dto) {
		Customer customer = customerDAO.findById(dto.getOrgNo());
		dto2entity(dto, customer);
		if (dto.getParentOrgNo() != -1 && !dto.getOrgNo().equals(dto.getParentOrgNo()) ) {
			customer.setParentOrg(companyDAO.findById(dto.getParentOrgNo()));
		} else {
			throw new ApplicationException("ERROR_PARENT_ORG_IS_SELF");
		}
		customerDAO.merge(customer);
	}

	/**
	 * 根据编号删除客户.
	 * 
	 * @param orgNo
	 *            机构编号：Long orgNo
	 */
	@Transactional()
	public void deleteCustomer(Long orgNo) {
		customerDAO.delete(customerDAO.findById(orgNo));
	}

	/**
	 * 批量删除客户.
	 * 
	 * @param orgNo
	 *            客户编号列表：Long[] orgNo
	 */
	@Transactional()
	public void deleteCustomer(Long[] orgNo) {
		customerDAO.deleteByIds(orgNo);
	}

	/**
	 * 根据ID查找客户信息.
	 * 
	 * @param id
	 *            客户编号：Long id return Customer
	 */
	@Transactional
	public Customer findCustomerById(Long id) {
		return customerDAO.findById(id);
	}

	/**
	 * 根据ID查找客户信息.
	 * 
	 * @param id
	 *            客户编号：Long id
	 */
	@Transactional
	public CustomerDTO findById(Long id) {
		CustomerDTO dto = new CustomerDTO();
		Customer entity = customerDAO.findById(id);
		CustomerDTO.entity2dto(entity, dto);
		if (entity != null && entity.getParentOrg() != null) {
			dto.setCompanyNo(entity.getParentOrg().getOrgNo());
		}
		return dto;
	}

	/**
	 * 导出数据字典到EXCEL.
	 * 
	 * @param customerQueryDTO
	 * @param sidx
	 * @param sord
	 * @return InputStream
	 */
	@SuppressWarnings("unchecked")
    @Transactional
	public InputStream exportCustomerItems(CustomerQueryDTO customerQueryDTO, String sidx, String sord) {

		LanguageContent lc = LanguageContent.getInstance();
		List<String[]> data = new ArrayList<String[]>();
		data.add(new String[] { lc.getContent("common.id"), lc.getContent("label.belongs.client"), lc.getContent("label.role.roleName"), lc.getContent("label.telephone"), lc.getContent("label.e-mail"), lc.getContent("label.address"), lc.getContent("setting.lable.fax") });// 加入表头

		PageDTO p = customerDAO.findPager(customerQueryDTO, sidx, sord);

		if (p != null && p.getData() != null && p.getData().size() > 0) {
			int i = 1;
			List<Customer> entities = p.getData();
			for (Customer customer : entities) {
				data.add(new String[] { i + "", companyDAO.findById(customer.getCompanyNo()).getOrgName().toString(), customer.getOrgName(), customer.getOfficePhone(), customer.getEmail(), customer.getAddress(), customer.getOfficeFax() });
				i++;
			}
		}

		StringWriter sw = new StringWriter();
		CSVWriter csvw = new CSVWriter(sw);
		csvw.writeAll(data);
		
		byte[] bs = null;
		try {
			bs = sw.getBuffer().toString().getBytes("GBK");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		ByteArrayInputStream stream = null;
		if(bs!=null){
			stream = new ByteArrayInputStream(bs);
		}
		try {
			if (csvw != null) {
				csvw.flush();
				csvw.close();
			}
			if (sw != null) {
				sw.flush();
				sw.close();
			}
		} catch (IOException e) {
			LOGGER.error(e);
		}
		return stream;
	}

	/**
	 * 从EXCEL文件导入数据.
	 * 
	 * @param customerQueryDTO
	 * @return import quantity
	 */
	@Transactional
	public Integer importCustomerItems(CustomerQueryDTO customerQueryDTO) {
		int result = -2;
		try {
			String fileEncode = FileEncodeUtils.getFileEncode(customerQueryDTO.getImportFile());
			Reader rd = new InputStreamReader(new FileInputStream(customerQueryDTO.getImportFile()),fileEncode);// 以字节流方式读取数据
			CSVReader reader = new CSVReader(rd);
			String[] line = null;

			Integer count = 0;
			Company company = new Company();
			while ((line = reader.readNext()) != null) {
			    // 默认的line.length = 1
			    // 空的就跳过
			    if (line.length == 1) {
			    	continue;
			    }
				Customer customer = customerDAO.findUniqueBy("orgName", line[1]);
				if (customer != null) {
					result = -1;
					break;
				} else {
					Customer entity = new Customer();
					if (StringUtils.hasText(line[0])){
						company = companyDAO.findUniqueBy("orgName", line[0].toString());
						if(company!=null){
							entity.setCompanyNo(company.getOrgNo());
							Organization org = organizationDAO.findById(company.getOrgNo());
							entity.setParentOrg(org);
							entity.setOrgName(line[1].toString());
							entity.setOfficePhone(line[2].toString());
							entity.setEmail(line[3].toString());
							entity.setAddress(line[4].toString());
							entity.setOfficeFax(line[5].toString());
							customerDAO.save(entity);
							count++;
						}else{
							result = -3;
							throw new ApplicationException("ERROR_CUSTOMER_COMPANY_NULL");
						}
					}
					
				}
			}
			result = count;
		} catch (Exception e1) {
			LOGGER.error(e1.getMessage());
		}
		return result;
	}
}
